import React, { useState, useCallback, useEffect } from 'react';
import { NavBar, Toast, Popup, ImageUploader } from 'antd-mobile';
import type { ImageUploadItem } from 'antd-mobile/es/components/image-uploader';
import { 
  DownOutline 
} from 'antd-mobile-icons';
import { useNavigate, useLocation } from 'react-router-dom';
import { RefundReason, PaymentMethod } from './types/refund';
import type { 
  OrderInfo, 
  RefundApplyForm, 
  RefundApiResponse
} from './types/refund';
import axios from 'axios';
import './Com/Refund.css';

const RefundApply: React.FC = () => {
  const navigate = useNavigate();
  const location = useLocation();
  
  // 表单状态
  const [formData, setFormData] = useState<RefundApplyForm>({
    selectedReason: '',
    customReason: '',
    uploadedPhotos: []
  });

  // 商品状态相关
  const [productStatus, setProductStatus] = useState<string>('');
  const [statusVisible, setStatusVisible] = useState<boolean>(false);
  
  // 订单信息状态
  const [orderInfo, setOrderInfo] = useState<OrderInfo | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  
  // 商品状态选项
  const statusOptions = [
    { key: 'not_picked', text: '未提货' },
    { key: 'picked', text: '已提货' }
  ];

  // 退款原因选项
  const refundReasons: RefundReason[] = [
    RefundReason.QUALITY_ISSUE,
    RefundReason.DESCRIPTION_MISMATCH,
    RefundReason.DAMAGED,
    RefundReason.OUT_OF_STOCK,
    RefundReason.NOT_SATISFIED,
    RefundReason.OTHER
  ];

  // 获取订单详情
  const fetchOrderDetails = useCallback((): void => {
    try {
      setLoading(true);
      
      // 从路由参数中获取订单信息
      const orderFromRoute = location.state?.order;
      
      console.log('接收到的订单信息:', orderFromRoute); // 调试日志
      
      if (!orderFromRoute) {
        Toast.show('未找到订单信息');
        navigate(-1);
        return;
      }

      // 直接使用传递过来的订单数据，转换为OrderInfo格式
      const orderData: OrderInfo = {
        orderId: orderFromRoute.orderId || '',
        productName: orderFromRoute.productName || '',
        productSpecs: '默认规格', // Order.tsx中没有productSpecs字段，使用默认值
        price: orderFromRoute.price || 0,
        quantity: orderFromRoute.quantity || 1,
        orderTime: orderFromRoute.orderTime || '',
        paymentMethod: (orderFromRoute.paymentMethod as PaymentMethod) || PaymentMethod.ALIPAY
      };
      
      console.log('转换后的订单信息:', orderData); // 调试日志
      
      setOrderInfo(orderData);
      setLoading(false);
    } catch (error) {
      console.error('处理订单信息失败:', error);
      Toast.show('处理订单信息失败');
      navigate(-1);
    }
  }, [location.state?.order, navigate]);

  // 组件挂载时获取订单详情
  useEffect(() => {
    fetchOrderDetails();
  }, [fetchOrderDetails]);

  // 上传照片处理
  const handlePhotoUpload = useCallback(async (file: File): Promise<ImageUploadItem> => {
    try {
      console.log('正在上传文件:', file.name);
      
      // 创建表单数据
      const formData = new FormData();
      formData.append('evidence', file);
      
      // 调用后端上传接口
      const response = await axios.post('http://localhost:3000/hy/yonghu/upload-evidence', formData, {
        headers: {
          'Content-Type': 'multipart/form-data',
        },
      });

      if (response.data.code === 200 && response.data.data) {
        const data = response.data.data;
        return {
          key: data.key,
          url: `http://localhost:3000${data.url}`
        };
      }
      
      throw new Error(response.data.message || '上传失败');
    } catch (error) {
      Toast.show('照片上传失败');
      console.error('Upload error:', error);
      throw error;
    }
  }, []);

  // 选择退款原因
  const handleReasonSelect = useCallback((reason: RefundReason): void => {
    setFormData(prev => ({
      ...prev,
      selectedReason: reason
    }));
  }, []);

  // 自定义原因输入
  const handleCustomReasonChange = useCallback((e: React.ChangeEvent<HTMLTextAreaElement>): void => {
    setFormData(prev => ({
      ...prev,
      customReason: e.target.value
    }));
  }, []);

  // 提交退款申请
  const handleSubmitRefund = useCallback(async (): Promise<void> => {
    if (!formData.selectedReason && !formData.customReason.trim()) {
      Toast.show('请选择或填写退款原因');
      return;
    }

    if (!orderInfo) {
      Toast.show('订单信息不存在');
      return;
    }

    try {
      // 模拟API调用
      const response: RefundApiResponse = {
        success: true,
        message: '退款申请提交成功'
      };

      if (response.success) {
        // 根据订单状态决定跳转页面和提示信息
        let targetPath = '';
        let successMessage = '';
        
        if (orderInfo.status === '待发货') {
          // 待发货订单，直接跳转到审核成功已退款页面
          targetPath = '/my/refund-success';
          successMessage = '退款申请提交成功，已为您完成退款';
        } else if (orderInfo.status === '待提货') {
          // 待提货订单，进入审核中页面
          targetPath = '/my/refund-pending';
          successMessage = '退款申请提交成功，请等待审核';
        } else {
          // 其他状态，默认进入审核中页面
          targetPath = '/my/refund-pending';
          successMessage = '退款申请提交成功，请等待审核';
        }

        Toast.show({
          content: successMessage,
          position: 'center',
          duration: 2000
        });

        // 延迟跳转到对应页面
        setTimeout(() => {
          navigate(targetPath, {
            state: {
              order: orderInfo,
              refundData: formData
            }
          });
        }, 2000);
      }
    } catch (error) {
      Toast.show('提交失败，请重试');
      console.error('Submit error:', error);
    }
  }, [formData, navigate, orderInfo]);

  // 删除上传的照片
  const handlePhotoDelete = useCallback((item: ImageUploadItem): void => {
    setFormData(prev => ({
      ...prev,
      uploadedPhotos: prev.uploadedPhotos.filter(photo => photo.key !== item.key)
    }));
  }, []);

  // 选择商品状态
  const handleStatusSelect = useCallback((key: string): void => {
    setProductStatus(key);
    setStatusVisible(false);
  }, []);

  // 获取状态显示文本
  const getStatusText = useCallback((key: string): string => {
    const option = statusOptions.find(item => item.key === key);
    return option ? option.text : '请选择';
  }, []);

  // 如果正在加载或订单信息不存在
  if (loading || !orderInfo) {
    return (
      <div className="refund-page">
        <NavBar 
          className="refund-navbar"
          onBack={() => navigate(-1)}
        >
          申请售后
        </NavBar>
        <div className="refund-container">
          <div style={{ 
            textAlign: 'center', 
            padding: '2rem', 
            fontSize: '0.36rem', 
            color: '#666' 
          }}>
            {loading ? '加载中...' : '订单信息不存在'}
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="refund-page">
      <NavBar 
        className="refund-navbar"
        onBack={() => navigate(-1)}
      >
        申请售后
      </NavBar>

      <div className="refund-container">
        {/* 温馨提示 */}
        <div className="refund-tip-section">
          <div className="refund-tip-title">温馨提示</div>
          <div className="refund-tip-content">
            请详细填写退款原因，并上传相关凭证照片。我们会在1-3个工作日内处理您的退款申请。
          </div>
        </div>

        {/* 订单信息 */}
        <div className="refund-card">
          <div className="refund-header">
            <div className="refund-status-title">订单信息</div>
          </div>
          <div className="refund-order-info">
            <div className="refund-order-row">
              <span className="refund-order-label">订单号:</span>
              <span className="refund-order-value">{orderInfo.orderId}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">商品名称:</span>
              <span className="refund-order-value">{orderInfo.productName}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">商品规格:</span>
              <span className="refund-order-value">{orderInfo.productSpecs}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">购买数量:</span>
              <span className="refund-order-value">{orderInfo.quantity}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">订单金额:</span>
              <span className="refund-order-value refund-price">¥{orderInfo.price}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">下单时间:</span>
              <span className="refund-order-value">{orderInfo.orderTime}</span>
            </div>
            <div className="refund-order-row">
              <span className="refund-order-label">支付方式:</span>
              <span className="refund-order-value">{orderInfo.paymentMethod}</span>
            </div>
          </div>
        </div>

        {/* 商品状态 */}
        <div className="refund-card">
          <div className="refund-reason-section">
            <div className="refund-reason-title">商品状态</div>
            <div 
              className="refund-status-selector"
              onClick={() => setStatusVisible(true)}
            >
              <span className="refund-status-text">
                {productStatus ? getStatusText(productStatus) : '请选择商品状态'}
              </span>
              <DownOutline className="refund-status-arrow" />
            </div>
          </div>
        </div>

        {/* 退款原因 */}
        <div className="refund-card">
          <div className="refund-reason-section">
            <div className="refund-reason-title">退款原因</div>
            <div style={{ marginBottom: '0.3rem' }}>
              {refundReasons.map((reason: RefundReason, index: number) => (
                <div
                  key={index}
                  style={{
                    display: 'flex',
                    alignItems: 'center',
                    marginBottom: '0.3rem',
                    cursor: 'pointer'
                  }}
                  onClick={() => handleReasonSelect(reason)}
                >
                  <div
                    style={{
                      width: '0.4rem',
                      height: '0.4rem',
                      borderRadius: '50%',
                      border: '2px solid #ff4757',
                      marginRight: '0.3rem',
                      backgroundColor: formData.selectedReason === reason ? '#ff4757' : 'transparent'
                    }}
                  />
                  <span style={{ fontSize: '0.36rem', color: '#333' }}>{reason}</span>
                </div>
              ))}
            </div>
            <textarea
              className="refund-reason-input"
              placeholder="请详细描述退款原因..."
              value={formData.customReason}
              onChange={handleCustomReasonChange}
              maxLength={200}
            />
            <div style={{ 
              fontSize: '0.32rem', 
              color: '#999', 
              textAlign: 'right',
              marginTop: '0.2rem'
            }}>
              {formData.customReason.length}/200
            </div>
          </div>
        </div>

        {/* 上传凭证 */}
        <div className="refund-card">
          <div className="refund-photos-section">
            <div className="refund-photos-title">上传凭证照片</div>
            <ImageUploader
              value={formData.uploadedPhotos}
              onChange={(items) => {
                setFormData(prev => ({
                  ...prev,
                  uploadedPhotos: items
                }));
              }}
              upload={handlePhotoUpload}
              onDelete={handlePhotoDelete}
              maxCount={3}
              accept="image/*"
              style={{ 
                '--cell-size': '2rem'
              }}
            />
            <div style={{ 
              fontSize: '0.3rem', 
              color: '#999', 
              marginTop: '0.3rem',
              lineHeight: '1.4'
            }}>
              最多可上传3张照片，支持jpg、png格式，单张图片不超过2MB
            </div>
          </div>
        </div>

        {/* 退款金额 */}
        <div className="refund-card">
          <div className="refund-order-row">
            <span className="refund-order-label">申请退款金额:</span>
            <span className="refund-order-value refund-price">¥{orderInfo.price}</span>
          </div>
        </div>
      </div>

      {/* 提交按钮 */}
      <div className="refund-actions">
        <button 
          className="refund-btn refund-btn-secondary"
          onClick={() => navigate(-1)}
        >
          取消
        </button>
        <button 
          className="refund-btn refund-btn-primary"
          onClick={handleSubmitRefund}
        >
          提交申请
        </button>
      </div>

      {/* 商品状态选择弹窗 */}
      <Popup
        visible={statusVisible}
        onMaskClick={() => setStatusVisible(false)}
        position="bottom"
        bodyStyle={{ paddingTop: 0 }}
      >
        <div style={{ padding: '0.4rem 0' }}>
          <div style={{ 
            textAlign: 'center', 
            fontSize: '0.36rem', 
            fontWeight: '600', 
            color: '#333',
            paddingBottom: '0.4rem',
            borderBottom: '1px solid #f0f0f0'
          }}>
            请选择商品状态
          </div>
          {statusOptions.map((option) => (
            <div
              key={option.key}
              style={{
                padding: '0.4rem',
                fontSize: '0.36rem',
                color: '#333',
                textAlign: 'center',
                cursor: 'pointer',
                borderBottom: '1px solid #f0f0f0'
              }}
              onClick={() => handleStatusSelect(option.key)}
            >
              {option.text}
            </div>
          ))}
          <div
            style={{
              padding: '0.4rem',
              fontSize: '0.36rem',
              color: '#999',
              textAlign: 'center',
              cursor: 'pointer'
            }}
            onClick={() => setStatusVisible(false)}
          >
            取消
          </div>
        </div>
      </Popup>
    </div>
  );
};

export default RefundApply; 